﻿using System;
using System.Collections.Generic;
using System.Linq;
using Google.GData.Client;
using Google.YouTube;
using System.Configuration;
using Google.GData.Extensions;
using Google.GData.Extensions.MediaRss;
using System.Text;
using log4net;

namespace FB.Utilities
{
    public class YouTubeVideoObject
    {
        public string VideoId { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public AtomCategoryCollection Categories { get; set; }
        public string Description { get; set; }
        public string Keywords { get; set; }
        public string Duration { get; set; }
        public bool Private { get; set; }
        public ExtensionCollection<MediaCategory> Tags { get; set; }
        public int ViewCount { get; set; }
        public double RatingAverage { get; set; }
        public Nullable<Guid> ChanelID { get; set; }
        public List<string> GetTagsList()
        {
            List<string> result = new List<string>();
            foreach (MediaCategory item in Tags)
            {
                result.Add(item.Value);
            }
            return result;
        }
        public string GetTagsString()
        {
            StringBuilder result = new StringBuilder();
            foreach (MediaCategory item in Tags)
            {
                result.Append(item.Value);
                result.Append(";");
            }
            return result.ToString();
        }
    }

    public class YouTubeVideoHelper
    {
        private static readonly ILog log = LogManager.GetLogger("YouTubeVideoObject");
        //const string YOUTUBE_CHANNEL = "thieunhi2014";
        //const string YOUTUBE_DEVELOPER_KEY = "AI39si6JqO_f2b_JWSV3QUbcwg5S-1RJ4-kiieosBZy9r1ORkCAv7BT5tLp579Tzmly8rvOVm3Jyueq3ZVqUNt1blS4DcoVppA";

        /// <summary>
        /// Feed video from chanel
        /// </summary>
        /// <param name="chanelID">chanelID</param>
        /// <param name="chanelName">chanelName</param>
        /// <param name="startIndex">Start feed index</param>
        /// <returns>Return list of YouTubeVideoObject. If error retrun null</returns>
        public static List<YouTubeVideoObject> GetVideosFromChanel(Guid chanelID, string chanelName, int startIndex)
        {
            List<YouTubeVideoObject> temp = new List<YouTubeVideoObject>();
            try
            {
                string DevKey = System.Configuration.ConfigurationManager.AppSettings["DevKey"].ToString();
                YouTubeRequestSettings settings = new YouTubeRequestSettings(chanelName + " Channel", DevKey);
                YouTubeRequest request = new YouTubeRequest(settings);
                if (startIndex < 1) startIndex = 1;
                string feedUrl = string.Format(
                    "http://gdata.youtube.com/feeds/api/users/{0}/uploads?orderby=published&start-index={1}&max-results=50&v=2"
                    , chanelName
                    , startIndex);
                Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
                if(videoFeed.TotalResults > 0)
                {
                    temp = (from video in videoFeed.Entries
                            select new YouTubeVideoObject() { 
                                VideoId = video.VideoId
                                , Title = video.Title
                                , Author = video.Author
                                , Categories = video.Categories
                                , Description = video.Description
                                , Keywords = video.Keywords
                                , Duration = video.Media.Duration.Seconds
                                , Private = video.Private
                                , Tags = video.Tags
                                , ViewCount = video.ViewCount
                                , RatingAverage = video.RatingAverage
                                , ChanelID = chanelID }).ToList();
                    }
                return temp;
            }
            catch(Exception ex)
            {
                log.Warn(ex.Message);
                return null;
            }
        }

        public static List<YouTubeVideoObject> GetVideosFromPlaylist(string playlistID)
        {
            string DevKey = System.Configuration.ConfigurationManager.AppSettings["DevKey"].ToString();
            YouTubeRequestSettings settings = new YouTubeRequestSettings(playlistID + " Playlist", DevKey);
            YouTubeRequest request = new YouTubeRequest(settings);

            string feedUrl = string.Format(
                "http://gdata.youtube.com/feeds/api/playlists/{0}&start-index=0&max-results=50&v=2"
                , playlistID);
            Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
            List<YouTubeVideoObject> temp = new List<YouTubeVideoObject>();
            if(videoFeed.TotalResults > 0)
            {
                temp = (from video in videoFeed.Entries
                        select new YouTubeVideoObject() { 
                    VideoId = video.VideoId
                    , Title = video.Title
                    , Author = video.Author
                    , Categories = video.Categories
                    , Description = video.Description
                    , Keywords = video.Keywords
                    , Duration = video.Media.Duration.Seconds
                    , Private = video.Private
                    , Tags = video.Tags
                    , ViewCount = video.ViewCount
                    , RatingAverage = video.RatingAverage
                    , ChanelID = null }).ToList();
                }
            return temp;
        }

        public static YouTubeVideoObject GetVideosByYoutubeID(string videoID)
        {
            try
            {
                string DevKey = System.Configuration.ConfigurationManager.AppSettings["DevKey"].ToString();
                YouTubeRequestSettings settings = new YouTubeRequestSettings(videoID + " Video", DevKey);
                YouTubeRequest request = new YouTubeRequest(settings);

                string feedUrl = String.Format("https://gdata.youtube.com/feeds/api/videos/{0}", videoID);

                Video videoFeed = request.Retrieve<Video>(new Uri(feedUrl));
                YouTubeVideoObject temp = new YouTubeVideoObject();

                temp.VideoId = videoFeed.VideoId;
                temp.Title = videoFeed.Title;
                temp.Author = videoFeed.Author;
                temp.Categories = videoFeed.Categories;
                temp.Description = videoFeed.Description;
                temp.Keywords = videoFeed.Keywords;
                temp.Duration = videoFeed.Media.Duration.Seconds;
                temp.Private = videoFeed.Private;
                temp.Tags = videoFeed.Tags;
                temp.ViewCount = videoFeed.ViewCount;
                temp.RatingAverage = videoFeed.RatingAverage;
                temp.ChanelID = null;
                return temp;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}